package com.parking.carsystem.parkingchargesystem.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.activity.ChooseLisencePlateActivity;
import com.parking.carsystem.parkingchargesystem.activity.LicensePlateAddActivity;
import com.parking.carsystem.parkingchargesystem.activity.SelfServicePaymentActivity;
import com.parking.carsystem.parkingchargesystem.adapter.ParkingPlateAdapter;
import com.parking.carsystem.parkingchargesystem.adapter.PaySettingAdapter;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.listener.OnclickItemPlateNumber;
import com.parking.carsystem.parkingchargesystem.module.GroupListModule;
import com.parking.carsystem.parkingchargesystem.module.InvoiceRecordModel;
import com.parking.carsystem.parkingchargesystem.module.ParkingCarMessageModule;
import com.parking.carsystem.parkingchargesystem.view.OnItemClickListener;
import com.parking.carsystem.parkingchargesystem.view.OnItemMenuClickListener;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenu;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuBridge;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuCreator;
import com.parking.carsystem.parkingchargesystem.view.SwipeMenuItem;
import com.parking.carsystem.parkingchargesystem.view.SwipeRecyclerView;
import com.parking.carsystem.parkingchargesystem.view.touch.OnItemStateChangedListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import ttyy.com.recyclerexts.base.EXTRecyclerAdapter;
import ttyy.com.recyclerexts.base.EXTViewHolder;

public class ChooseLisensePlateFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.me_car_message)
    SwipeRecyclerView meCarMessage;
    @BindView(R.id.search_paking)
    TextView searchPaking;
    Unbinder unbinder;
    private ChooseLisencePlateActivity activity;
    public GroupListModule.DataBean.VehiclesBean vehicleModule;
    public ParkingPlateAdapter parkingPlateAdapterData;
    private String payment;
    ArrayList<GroupListModule.DataBean.VehiclesBean> vehicles ;
    private ParkingPlateAdapter parkingPlateAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_choose_lisence_plate, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        initView();
        initData();
        return inflate;
    }

    private void initData() {
        meCarMessage.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (vehicles == null) {
            vehicles = new ArrayList<>();
        }
        parkingPlateAdapter = new ParkingPlateAdapter(vehicles, activity);
        meCarMessage.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                menuBridge.closeMenu();
                GroupListModule.DataBean.VehiclesBean vehiclesBean1 = vehicles.get(position);
                int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
                int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

                if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                    Toast.makeText(getActivity(), "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                            .show();
                    vehicles.remove(vehiclesBean1);
                    parkingPlateAdapter.setDatas(vehicles);
                    //直接删除列表,不同步网络请求
                    deleteParkingPlate(vehiclesBean1);
                } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
                    Toast.makeText(getActivity(), "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }); // Item的Menu点击。
        meCarMessage.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
                int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

                // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
                // 2. 指定具体的高，比如80;
                // 3. WRAP_CONTENT，自身高度，不推荐;
//                int height = ViewGroup.LayoutParams.MATCH_PARENT;
                int height = getResources().getDimensionPixelSize(R.dimen.dp_62);

                // 添加左侧的，如果不添加，则左侧不会出现菜单。
            /*{
                SwipeMenuItem addItem = new SwipeMenuItem(getActivity()).setBackground(
                        R.drawable.selector_green).setImage(R.drawable.ic_action_add).setWidth(width).setHeight(height);
                swipeLeftMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。

                SwipeMenuItem closeItem = new SwipeMenuItem(BaseDragActivity.this).setBackground(
                        R.drawable.selector_red).setImage(R.drawable.ic_action_close).setWidth(width).setHeight(height);

                swipeLeftMenu.addMenuItem(closeItem); // 添加一个按钮到左侧菜单。
            }*/

                // 添加右侧的，如果不添加，则右侧不会出现菜单。
                if (parkingPlateAdapter.getItemViewType(position) == Constant.VIEWTYPE_OTHER) {
                    {
                        SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()).setBackground(
                                R.drawable.parking_plate_red)
//                        .setImage(R.drawable.ic_action_delete)
                                .setText("删除")
                                .setTextColor(Color.WHITE)
                                .setWidth(width)
                                .setHeight(height);
                        swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

                /*SwipeMenuItem closeItem = new SwipeMenuItem(BaseDragActivity.this).setBackground(
                        R.drawable.selector_purple).setImage(R.drawable.ic_action_close).setWidth(width).setHeight(height);
                swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。*/
                    }
                }
            }
        }); // 菜单创建器。
//                meCarMessage.setOnItemMoveListener(getItemMoveListener());// 监听拖拽和侧滑删除，更新UI和数据源。
//                meCarMessage.setOnItemStateChangedListener(mOnItemStateChangedListener); // 监听Item的手指状态，拖拽、侧滑、松开。
//                meCarMessage.setLongPressDragEnabled(true); // 长按拖拽，默认关闭。
//                meCarMessage.setItemViewSwipeEnabled(false); // 滑动删除，默认关闭。
        meCarMessage.setOnItemClickListener(new com.parking.carsystem.parkingchargesystem.view.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int adapterPosition) {
                GroupListModule.DataBean.VehiclesBean vehiclesBean1 = vehicles.get(adapterPosition);
                Log.d("parking", "第" + adapterPosition + "个");
                if (vehiclesBean1.itemType.equals("1")) {
                    //添加车牌
//                    Toast.makeText(getActivity(), "添加车牌", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getActivity(), LicensePlateAddActivity.class);
                    startActivityForResult(intent, Constant.ADDPARKINGCODE);
                } else if (vehiclesBean1.itemType.equals("3")) {
                    if (vehicleModule != null) {
                        if (vehicleModule != vehiclesBean1) {
                            //点击的不是同一个条目的对象,状态置为false,
                            vehicleModule.chooseItem = false;
                        }
                    }
                    if (parkingPlateAdapterData != null) {
                        if (parkingPlateAdapterData != parkingPlateAdapter) {
                            //如果点击的atapter不是同一个,把上一个更新,根据上面的对象状态置为false,然后把上一个点击的item置为未选中
                            parkingPlateAdapterData.notifyDataSetChanged();
                        }
                    }
                    //点击的是同一个adapter,不是同一个module或者是同一个module,都走这个遍历改变当前点击的集合里面的数据状态
                    for (GroupListModule.DataBean.VehiclesBean vehicle : vehicles) {
                        if (vehicle.id == vehiclesBean1.id) {
                            if (vehicle.chooseItem) {
                                vehicle.chooseItem = false;
                            } else {
                                vehicle.chooseItem = true;
                            }
                            vehicleModule = vehicle;
                        } else {
                            vehicle.chooseItem = false;
                        }
                    }
                    parkingPlateAdapterData = parkingPlateAdapter;
                    parkingPlateAdapter.notifyDataSetChanged();
                }
            }
        });
        meCarMessage.setAdapter(parkingPlateAdapter);
        getGroupList();
    }

    private void deleteParkingPlate(GroupListModule.DataBean.VehiclesBean vehiclesBean1) {
        //删除指定分组的车牌
        OkGo.<String>delete(Constant.url + Constant.DELETEPARKING + vehiclesBean1.parentId)
                .params("plateNumber", vehiclesBean1.plateNumber)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {
                    }
                });
    }

    private void initView() {
        activity = (ChooseLisencePlateActivity) getActivity();
        searchPaking.setOnClickListener(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_paking:
                //查询未交的停车费
                if (vehicleModule != null && vehicleModule.chooseItem) {
                    if (TextUtils.isEmpty(payment)) {
                        Intent intent = new Intent(activity, SelfServicePaymentActivity.class);
                        intent.putExtra(Constant.PLATENUMBER, vehicleModule.plateNumber);
                        startActivity(intent);
                    } else {
                        //关闭当前界面
                        Intent intent = new Intent();
                        intent.putExtra(Constant.PLATENUMBER, vehicleModule.plateNumber);
                        intent.putExtra(Constant.PLATECOLOR, vehicleModule.plateColor);
                        activity.setResult(Constant.PLATENUMBERCODE, intent);
                        activity.finish();
                    }
                } else {
                    activity.showToast("请选择你要查询的车牌");
                }
                break;
        }
    }

    /**
     * 获取分组列表
     */
    public void getGroupList() {
        activity.showLoading();
        OkGo.<String>get(Constant.url + Constant.GROUP_LIST_DATA)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        activity.stopLoading();
                        Gson gson = new Gson();
                        GroupListModule groupListModule = gson.fromJson(response.body(), GroupListModule.class);
                        if (groupListModule.code == 200) {
                            vehicles.clear();
                            //把所有的数据放到一个集合里面
                            for (GroupListModule.DataBean datum : groupListModule.data) {
                                GroupListModule.DataBean.VehiclesBean vehiclesBean = new GroupListModule.DataBean.VehiclesBean();
                                vehiclesBean.plateNumber = datum.groupName;
                                vehiclesBean.itemType = "2";
                                vehiclesBean.parentId = datum.id;
                                vehicles.add(vehiclesBean);
                                for (GroupListModule.DataBean.VehiclesBean vehicle : datum.vehicles) {
                                    vehicle.parentId = datum.id;
                                    vehicle.itemType = "3";
                                    vehicles.add(vehicle);
                                }
                                GroupListModule.DataBean.VehiclesBean vehiclesBean1 = new GroupListModule.DataBean.VehiclesBean();
                                vehiclesBean1.plateNumber = "添加车牌";
                                vehiclesBean1.itemType = "1";
                                vehicles.add(vehiclesBean1);
                            }
                            parkingPlateAdapter.setDatas(vehicles);
                        } else {
                            activity.showToast(response.message());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        activity.showToast(response.message());
                        activity.stopLoading();
                    }
                });
    }

    public void setPayMent(String payment) {
        this.payment = payment;
    }
}
